var connection = new WebSocket('ws://39.106.188.158:8888'),  //39.106.188.158是服务器的地址
    name = "";

var loginPage = document.querySelector('#login-page'),
    usernameInput = document.querySelector('#username'),
    loginButton = document.querySelector('#login'),
    callPage = document.querySelector('#call-page'),
    theirUsernameInput = document.querySelector('#their-username'),
    callButton = document.querySelector('#call'),
    hangUpButton = document.querySelector('#hang-up'),
    btnStartRecording = document.querySelector('#startSave'),
    btnStopRecording  = document.querySelector('#stopSave');

var record;
var timerID;
var time=10;//60*3;  //3分钟

// this function submits recorded blob to nodejs server

//通过blob，封装成一个文件
function postFiles() {
      var blob = recorder.getBlob();
      // getting unique identifier for the file name
      var fileName = generateRandomString() + '.webm'; 
      var file = new File([blob], fileName, {
          type: 'video/webm'
      });
      xhr('/uploadFile', file, function(responseText) {
          //上传文件到后台后的回调函数
      });
}

// XHR2/FormData   
//通过XHR2将前端的保存文件上传到后台
function xhr(url, data, callback) {
    var request = new XMLHttpRequest();
    request.onreadystatechange = function() {
        if (request.readyState == 4 && request.status == 200) {
            callback(request.responseText);
        }
    };
            
   
    request.open('POST', url);

    var formData = new FormData();
    formData.append('file', data);
    request.send(formData);
}

// generating random string
function generateRandomString() {
    if (window.crypto) {
        var a = window.crypto.getRandomValues(new Uint32Array(3)),
            token = '';
        for (var i = 0, l = a.length; i < l; i++) token += a[i].toString(36);
        return token;
    } else {
        return (Math.random() * new Date().getTime()).toString(36).replace( /\./g , '');
    }
}

// function captureUserMedia(success_callback) {
//   function hasUserMedia() {
//      return !!(navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia);
//    }

//  if (hasUserMedia()) {
//      navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;

//      var constraints = {
//        video: {
//          mandatory: {
//            minWidth: 640,
//            minHeight: 480
//          }
//        },
//        audio: true
//      };

//      if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) {
//        // The user is using a mobile device, lower our minimum resolution
//        constraints = {
//          video: {
//            mandatory: {
//              minWidth: 480,
//              minHeight: 320,
//              maxWidth: 1024,
//              maxHeight: 768
//            }
//          },
//          audio: true
//        };
//      }

//      navigator.getUserMedia(constraints, success_callback, function (error) {
//        console.log("Raised an error when capturing:", error);
//      });
//   } 
//   else 
//   {
//     alert("Sorry, your browser does not support getUserMedia.");
//   }
// }



callPage.style.display = "none";

// Login when the user clicks the button
loginButton.addEventListener("click", function (event) {
  name = usernameInput.value;

  if (name.length > 0) {
    send({
      type: "login",
      name: name
    });
  }
});

connection.onopen = function () {
  console.log("Connected");
};

// Handle all messages through this callback
connection.onmessage = function (message) {
  console.log("Got message", message.data);

  var data = JSON.parse(message.data);

  switch(data.type) {
    case "login":
      onLogin(data.success);
      break;
    case "offer":
      onOffer(data.offer, data.name);
      break;
    case "answer":
      onAnswer(data.answer);
      break;
    case "candidate":
      onCandidate(data.candidate);
      break;
    case "leave":
      onLeave();
      break;
    default:
      break;
  }
};

connection.onerror = function (err) {
  console.log("Got error", err);
};

// Alias for sending messages in JSON format
function send(message) {
  if (connectedUser) {
    message.name = connectedUser;
  }

  connection.send(JSON.stringify(message));
};

function onLogin(success) {
  if (success === false) {
    alert("Login unsuccessful, please try a different name.");
  } else {
    loginPage.style.display = "none";
    callPage.style.display = "block";

    // Get the plumbing ready for a call
    startConnection();
  }
};

callButton.addEventListener("click", function () {
  var theirUsername = theirUsernameInput.value;

  if (theirUsername.length > 0) {
    startPeerConnection(theirUsername);
  }
});

hangUpButton.addEventListener("click", function () {
  send({
    type: "leave"
  });

  onLeave();
});

function onOffer(offer, name) {
  connectedUser = name;
  yourConnection.setRemoteDescription(new RTCSessionDescription(offer));

  yourConnection.createAnswer(function (answer) {
    yourConnection.setLocalDescription(answer);
    console.log("answer");
    send({
      type: "answer",
      answer: answer
    });
  }, function (error) {
    alert("An error has occurred");
  });
}

function onAnswer(answer) {
  yourConnection.setRemoteDescription(new RTCSessionDescription(answer));
};

function onCandidate(candidate) {
  yourConnection.addIceCandidate(new RTCIceCandidate(candidate));
};

function onLeave() {
  connectedUser = null;
  theirVideo.src = null;
  yourConnection.close();
  yourConnection.onicecandidate = null;
  yourConnection.onaddstream = null;
  recorder.stopRecording(postFiles);
  setupPeerConnection(stream);
};

function hasUserMedia() {
  navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
  return !!navigator.getUserMedia;
};

function hasRTCPeerConnection() {
  window.RTCPeerConnection = window.RTCPeerConnection || window.webkitRTCPeerConnection || window.mozRTCPeerConnection;
  window.RTCSessionDescription = window.RTCSessionDescription || window.webkitRTCSessionDescription || window.mozRTCSessionDescription;
  window.RTCIceCandidate = window.RTCIceCandidate || window.webkitRTCIceCandidate || window.mozRTCIceCandidate;
  return !!window.RTCPeerConnection;
};

var theirVideo = document.querySelector('#theirs'),
    yourConnection, connectedUser, stream;

function startConnection() {
  // if (hasUserMedia()) {
  //   navigator.getUserMedia({ video: true, audio: false }, function (myStream) {
  //     stream = myStream;
  //     yourVideo.src = window.URL.createObjectURL(stream);

  //     if (hasRTCPeerConnection()) {
  //       setupPeerConnection(stream);
  //     } else {
  //       alert("Sorry, your browser does not support WebRTC.");
  //     }
  //   }, function (error) {
  //     console.log(error);
  //   });
  // } else {
  //   alert("Sorry, your browser does not support WebRTC.");
  // }
  var configuration = {
    "iceServers": [{ "url": "stun:127.0.0.1:9876" }]
  };
  yourConnection = new RTCPeerConnection(configuration);
  yourConnection.onaddstream = function (e) {
    theirVideo.src = window.URL.createObjectURL(e.stream);
    captureUserMedia(e.stream);
  };
  yourConnection.onicecandidate = function (event) {
    if (event.candidate) {
      console.log("onicecandidate");
      send({
        type: "candidate",
        candidate: event.candidate
      });
    }
  };

};

function save(){
  recorder.stopRecording(postFiles);
  recorder.clearRecordedData();
  recorder.startRecording();
}

function captureUserMedia(stream)
{
  timerID=window.setInterval(save,time*1000);
  recorder = RecordRTC(stream,{type: 'video'});
  recorder.startRecording();  
}

function setupPeerConnection(stream) {
  var configuration = {
    "iceServers": [{ "url": "stun:127.0.0.1:9876" }]
  };
  yourConnection = new RTCPeerConnection(configuration);

  // Setup stream listening
  yourConnection.addStream(stream);
  yourConnection.onaddstream = function (e) {
    theirVideo.src = window.URL.createObjectURL(e.stream);
    captureUserMedia(e.stream);
  };

  // Setup ice handling
  yourConnection.onicecandidate = function (event) {
    if (event.candidate) {
      console.log("onicecandidate");
      send({
        type: "candidate",
        candidate: event.candidate
      });
    }
  };
};

function startPeerConnection(user) {
  connectedUser = user;

  // Begin the offer
  yourConnection.createOffer(function (offer) {
    console.log("offer");
    send({
      type: "offer",
      offer: offer
    });
    yourConnection.setLocalDescription(offer);
    console.log(JSON.stringify(offer));
  }, function (error) {
    alert("An error has occurred.");
  });
};
